import { defineComponent } from 'vue';
import { getReturnCase } from '@/api/home';
import SheltV2 from '../../common/SheltV2';
import Echarts from '@/components/Echarts';
import { productType } from '../../../Enum';
import {
  ElDatePicker,
  ElDialog,
  ElOption,
  ElPagination,
  ElSelect,
  ElTable,
  ElTableColumn
} from 'element-plus';
import './index.less';
export default defineComponent({
  name: 'Return',
  props: {
    type: {
      type: String,
      default: 'small'
    },
    aspectRatio: {
      type: String,
      default: '2/1'
    }
  },
  setup(props: any) {
    const dialogVisible = ref(false);
    const loading = ref(false);
    const tableData = ref([]);
    const initData = ref({ date: new Date(), type: 1 }) as AnyObject;
    const pageable = ref({
      type: 1,
      page: 1,
      pageSize: 15,
      date: new Date(),
      avarRate: '',
      count: 0,
      total: 0
    }) as AnyObject;

    const obj = {
      big: {
        ti_l: '24%',
        len: 50,
        center: ['25%', '50%'],
        legend: { right: '10%' }
      },
      normal: {},
      small: {
        ti_l: '74%',
        len: 16,
        center: ['75%', '50%'],
        legend: { left: 'left' }
      }
    } as AnyObject;
    const option = ref({
      tooltip: {
        trigger: 'item'
      },
      title: {
        text: '', //主标题文本，'\n'指定换行
        subtext: '本月退货率',
        left: obj[props.type].ti_l,
        textAlign: 'center',
        y: 'center',
        textStyle: {
          color: '#000',
          fontSize: 24
        },
        subtextStyle: {
          color: '#666666',
          fontSize: '12px'
        },
        itemGap: 0
      },
      color: [
        '#ffb17d',
        '#ffc824',
        '#63d3ff',
        '#40a6ff',
        '#4a74ea',
        '#1ac48b',
        '#fc8844',
        'gray'
      ],
      legend: {
        orient: 'vertical',
        top: 'center',
        ...obj[props.type].legend,
        icon: 'circle',
        itemWidth: 10,
        textStyle: {
          rich: {
            a: {
              fontSize: 12,
              color: '#666666'
            }
          }
        }
      },
      series: [
        {
          name: '退货情况',
          type: 'pie',
          radius: ['70%', '90%'],
          avoidLabelOverlap: false,
          center: obj[props.type].center,
          itemStyle: {
            borderRadius: 2
          },
          label: {
            show: false
            // fontSize:12
            // formatter: '{a|{c}}\n\r{b|{b}}',
          },
          labelLine: {
            show: true,
            length: 5
          },
          data: []
        }
      ]
    }) as any;
    const detailSlots = ref({
      detail: () => {
        return (
          <div class="item_right">
            <ElSelect
              style={{ width: '100px' }}
              v-model={initData.value.type}
              onChange={handleChange}
              placeholder="产品类型"
            >
              {productType.map((_item) => (
                <ElOption
                  key={_item.value}
                  label={_item.label}
                  value={_item.value}
                ></ElOption>
              ))}
            </ElSelect>
            <ElDatePicker
              v-model={initData.value.date}
              type="month"
              class="month_selector"
              range-separator="/"
              clearable={false}
              // @ts-ignore
              onChange={handleChange}
            />
          </div>
        );
      }
    });
    const handleChange = () => {
      getReturnCaseData();
    };
    const viewDetail = () => {
      const { datas, amount, ...asets } = initData.value;
      tableData.value = datas;
      Object.assign(pageable.value, asets);
      dialogVisible.value = true;
    };
    const handleSizeChange = (pageSize: number) => {
      pageable.value.pageSize = pageSize;
      handleSelect();
    };
    const handleCurrentChange = (page: number) => {
      pageable.value.page = page;
      handleSelect();
    };

    const handleSelect = () => {
      loading.value = true;
      const month = ('' + (pageable.value.date.getMonth() + 1)).padStart(
        2,
        '0'
      );
      const year = pageable.value.date.getFullYear();
      getReturnCase({
        page: pageable.value.page,
        pageSize: pageable.value.pageSize,
        month: year + '-' + month,
        type: pageable.value.type
      }).then((res: AnyObject) => {
        // if (!res.total) {
        //   loading.value = false;
        //   return;
        // }
        const { datas, amount, ...asset } = res;
        tableData.value = datas;
        Object.assign(pageable.value, asset);
        loading.value = false;
      });
    };
    getReturnCaseData();
    function getReturnCaseData() {
      const date = initData.value.date;
      const month = ('' + (date.getMonth() + 1)).padStart(2, '0');
      const year = date.getFullYear();
      getReturnCase({
        page: 1,
        pageSize: 15,
        month: year + '-' + month,
        type: initData.value.type
      }).then((res: AnyObject) => {
        // if (!res.total) {
        //   return;
        // }
        Object.assign(initData.value, res);
        const _arr = [] as any;
        res.datas.slice(0, 7)?.forEach((_item: AnyObject, _index: number) => {
          _arr[_index] = {
            name: _item.configName,
            value: _item.thisRefundRate
          };
        });

        option.value.series[0].data = _arr;
        option.value.title.text = res.thisRate + '%';
        option.value.legend.formatter = (name: string) => {
          const findItem = _arr?.find(
            (_item: AnyObject) => _item.name === name
          );
          const joinText = findItem
            ? name + '     ' + findItem.value + '%'
            : '';
          const revealName =
            joinText.length > obj[props.type].len
              ? joinText.slice(0, obj[props.type].len) + '...'
              : joinText;
          return `{a|${revealName}}`;
        };
      });
    }
    return () => (
      <SheltV2
        title="退货情况"
        question="<div><p>【该数据每日02:00更新一次】</p><p>退货情况数据来源于BI，统计直营电商亚马逊的退货数据。</p></div>"
        more="查看全部"
        v-slots={detailSlots.value}
        onViewDetail={viewDetail}
      >
        <Echarts aspectRatio={props.aspectRatio} option={option.value} />
        {Boolean(initData.value.total) && (
          <p class="fill_legend flex-start">
            <div class="circle"></div>
            <span>其他</span>
            <span>...</span>
          </p>
        )}
        <ElDialog
          lock-scroll
          draggable
          v-model={dialogVisible.value}
          title="历史退货情况"
          style={{ maxWidth: '800px', with: 'auto' }}
        >
          <div class="flex-between">
            <ElSelect
              v-model={pageable.value.type}
              style={{ width: '100px' }}
              onChange={handleSelect}
              placeholder="产品类型"
            >
              {productType.map((_item) => (
                <ElOption
                  key={_item.value}
                  label={_item.label}
                  value={_item.value}
                ></ElOption>
              ))}
            </ElSelect>
            <ElDatePicker
              v-model={pageable.value.date}
              type="month"
              class="month_selector"
              range-separator="-"
              clearable={false}
              // @ts-ignore
              onChange={handleSelect}
            />
            <div class="table_header_item">
              <p>当月销售数：{pageable.value.thisCount}</p>
              <p> 近6个月销售数：{pageable.value.monthCount}</p>
            </div>
            <div class="table_header_item">
              <p>当月退货数：{pageable.value.thisRefundCount}</p>
              <p> 近6个月退货数：{pageable.value.monthRefundCount}</p>
            </div>
            <div class="table_header_item">
              <p>当月退货率：{pageable.value.thisRate}%</p>
              <p> 近6个月退货率：{pageable.value.monthRate}%</p>
            </div>
          </div>

          <ElTable
            v-loading={loading.value}
            header-row-class-name="table_header"
            size="small"
            data={tableData.value}
          >
            <ElTableColumn prop="configName" label="产品名称" />
            <ElTableColumn prop="thisMonthQuantity" label="当月销售数" />
            <ElTableColumn prop="monthQuantity" label="近6个月销售数" />
            <ElTableColumn prop="thisMonthRefundQuantity" label="当月退货数" />
            <ElTableColumn prop="monthRefundQuantity" label="近6个月退货数" />
            <ElTableColumn
              label="当月退货率"
              v-slots={{
                default: ({ row }: AnyObject) => <p>{row.thisRefundRate}%</p>
              }}
            />
            <ElTableColumn
              label="近6个月退货率"
              v-slots={{
                default: ({ row }: AnyObject) => <p>{row.monthRefundRate}%</p>
              }}
            />
          </ElTable>
          <ElPagination
            v-model:current-page={pageable.value.page}
            v-model:page-size={pageable.value.pageSize}
            small
            page-sizes={[15, 30, 50, 100]}
            hide-on-single-page
            layout="total, sizes, prev, pager, next, jumper"
            total={pageable.value.total}
            onSize-change={handleSizeChange}
            onCurrent-change={handleCurrentChange}
          ></ElPagination>
        </ElDialog>
      </SheltV2>
    );
  }
});
